package behaviours.inventor;

import behaviours.curator.*;
import java.io.IOException;

import com.myprofile.profile.MuseumItem;

import resource.TourItem;
import agents.InventorAgent;
import jade.core.AID;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;

public class ListenForTourItemQuestions extends CyclicBehaviour {

	private InventorAgent inventorAgent;

	public ListenForTourItemQuestions(InventorAgent agent){
		super(agent);
		this.inventorAgent = agent;
	}
	
	@Override
	public void action() {
		ACLMessage msg = inventorAgent.receive(MessageTemplate.MatchPerformative(ACLMessage.REQUEST));
		if (msg != null){
                    System.out.println("Inventor: Received item info request");
			TourItem tourItem = null;
			try {
				tourItem = (TourItem)msg.getContentObject();
			} catch (UnreadableException e) { /*DO NOTHING IT WILL BE NULL AND I HANDLE IT LATER*/ }
			
			if (tourItem != null){
				String id = tourItem.getId();
				
				MuseumItem itemToReturn = null;
				for (MuseumItem item : inventorAgent.allItems){
					if (item.getId().equals(id)){
						itemToReturn = item;
						break;
					}
				}
				
				if (itemToReturn != null){
					ACLMessage returnMsg = new ACLMessage(ACLMessage.INFORM);
					returnMsg.setSender(inventorAgent.getAID());
					returnMsg.addReceiver(msg.getSender());
					try {
						returnMsg.setContentObject(itemToReturn);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					inventorAgent.send(returnMsg);
                                        System.out.println("Inventor: Sent item info");
				} else {
					sendNotUnderstood(msg.getSender());
				}
			} else {
				sendNotUnderstood(msg.getSender());
			}
		} else {
			block();
		}
	}

	private void sendNotUnderstood(AID sendTo) {
		ACLMessage returnMsg = new ACLMessage(ACLMessage.NOT_UNDERSTOOD);
		returnMsg.setSender(inventorAgent.getAID());
		returnMsg.addReceiver(sendTo);

		inventorAgent.send(returnMsg);
	}

}
